﻿using System;
using System.Web;
using CourseManager.Model.Data;
using CourseManager.Model.Util;
using Ext.Net;
using log4net;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace CourseManager.View
{
	public partial class Login : System.Web.UI.Page
	{
		private static readonly ILog log = LogManager.GetLogger(typeof(Login).Name);

		protected void Page_Load(object sender, EventArgs e)
		{
		}

		/// <summary>
		/// 刷新验证码
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected  void EimgValidChange(object sender, EventArgs e)
		{
			eimgValid.ImageUrl = "CheckCodeImage.aspx?x=" + new Random().Next(99999);
		}

		/// <summary>
		/// 登陆按钮事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void BtnLoginClick(object sender, EventArgs e)
		{
			if(!txtCode.Text.Trim().ToLower().Equals(Session["CheckCode"]))
			{
				X.Msg.Alert("提示", "验证码错误");
				txtCode.Focus();
			} 
			else
			{
				string userId = txtName.Text.Trim();
				string password = CMUtils.EncodeMD5(txtPass.Text.Trim());
				
				Tab_User user = UserDAO.FindById(userId);
				if(user != null)
					log.Info(string.Format("Login: name:{0}, pwd1={1}, pwd2={2}", userId, password, user.password));

				if (user == null || !user.password.Equals(password))
				{
					X.Msg.Alert("提示", "用户名或密码错误");
					txtCode.Text = string.Empty;
					txtPass.Focus();
				}
				else
				{
					string ip = HttpContext.Current.Request.UserHostAddress;
					LogDAO.add(user.userId, ip, "Login", DateTime.Now);
					Session["UserId"] = user.userId;
					Session["AccountType"] = user.type;
					Response.Redirect("Main.aspx");
				}
			}
			EimgValidChange(sender, e);
		}
	}
}